using GameConfig.item;
using TEngine;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace GameLogic
{
    public class SlotUI : MonoBehaviour, IPointerClickHandler, IBeginDragHandler, IDragHandler, IEndDragHandler
    {
        [Header("组件获取")]
        [SerializeField] private Image slotImage;
        [SerializeField] private Text amountText;
        public Image slotHightlight;
        [SerializeField] private Button button;

        [Header("格子类型")]
        public SlotType slotType;
        public bool isSelected;
        public int slotIndex;

        //物品信息
        public ItemTb itemDetails;
        public int itemAmount;

        public InventoryLocation Location
        {
            get
            {
                return slotType switch
                {
                    SlotType.Bag => InventoryLocation.Player,
                    SlotType.Box => InventoryLocation.Box,
                    _ => InventoryLocation.Player
                };
            }
        }

        //public InventoryUI inventoryUI => GetComponentInParent<InventoryUI>();

        private void Start()
        {
            isSelected = false;
            if (itemDetails == null)
            {
                UpdateEmptySlot();
            }
        }

        /// <summary>
        /// 更新格子UI和信息
        /// </summary>
        /// <param name="item">ItemDetails</param>
        /// <param name="amount">持有数量</param>
        public void UpdateSlot(ItemTb item, int amount)
        {
            if (item == null)
            {
                slotImage.gameObject.SetActive(false);
                amountText.gameObject.SetActive(false);
                itemDetails = null;
                itemAmount = 0;
            }
            else
            {
                slotImage.gameObject.SetActive(true);
                amountText.gameObject.SetActive(true);
                itemDetails = item;
                slotImage.sprite = GameModule.Resource.LoadAsset<Sprite>(item.ItemIcon);
                itemAmount = amount;
                amountText.text = amount.ToString();
                slotImage.enabled = true;
                button.interactable = true;
            }
        }

        /// <summary>
        /// 将Slot更新为空
        /// </summary>
        public void UpdateEmptySlot()
        {
            if (isSelected)
            {
                isSelected = false;

            }
            itemDetails = null;
            slotImage.enabled = false;
            amountText.text = string.Empty;
            button.interactable = false;
        }

        public void IsSelect(bool isSelect)
        {
            slotHightlight.gameObject.SetActive(isSelect);
            if (isSelect)
            {
                
            }
            else
            {

            }
        }

        public void OnPointerClick(PointerEventData eventData)
        {
            if (itemDetails == null) return;
            isSelected = !isSelected;

            GameEvent.Get<ILoginUI>().SelectSlotUI(slotIndex);

            if (slotType == SlotType.SlotUI)
            {
                //通知物品被选中的状态和信息
                //EventHandler.CallItemSelectedEvent(itemDetails, isSelected);
                GameEvent.Get<ILoginUI>().OnItemSelectedEvent(itemDetails, isSelected);
            }
        }

        public void OnBeginDrag(PointerEventData eventData)
        {
            if (itemAmount != 0)
            {
                UIModule.Instance.GetUIAsync<MainUI>((data) =>
                {
                    data.dragPanel.dragItem.enabled = true;
                    data.dragPanel.dragItem.sprite = slotImage.sprite;
                });
                isSelected = true;
                PlayerSlotInventoryPanel.instance.SelectSlotUI(slotIndex,isSelected);
            }
        }

        public void OnDrag(PointerEventData eventData)
        {
            Vector2 mousePos;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(
                UIModule.UIRoot.GetComponent<RectTransform>(),
                Input.mousePosition,
                UIModule.Instance.UICamera,
                out mousePos
            );

            // 更新 UI 位置
            UIModule.Instance.GetUIAsync<MainUI>((data) =>
            {
                data.dragPanel.dragItem.rectTransform.anchoredPosition = mousePos;
            });
        }

        public void OnEndDrag(PointerEventData eventData)
        {
            UIModule.Instance.GetUIAsync<MainUI>((data) =>
            {
                data.dragPanel.dragItem.enabled = false;
            });
            Debug.Log(eventData.pointerCurrentRaycast.gameObject);

            if (eventData.pointerCurrentRaycast.gameObject != null)
            {
                if (eventData.pointerCurrentRaycast.gameObject.GetComponent<SlotUI>() == null)
                    return;

                var targetSlot = eventData.pointerCurrentRaycast.gameObject.GetComponent<SlotUI>();
                int targetIndex = targetSlot.slotIndex;

                //在Player自身背包范围内交换
                if (slotType == SlotType.SlotUI && targetSlot.slotType == SlotType.SlotUI)
                {
                    InventoryManager.Instance.SwapSlotUIItem(slotIndex, targetIndex);
                }
                else if (slotType == SlotType.SlotUI && targetSlot.slotType == SlotType.Bag)
                {

                }
                else if (slotType == SlotType.Shop && targetSlot.slotType == SlotType.Bag)  //买
                {
                    //EventHandler.CallShowTradeUI(itemDetails, false);
                }
                else if (slotType == SlotType.Bag && targetSlot.slotType == SlotType.Shop)  //卖
                {
                    //EventHandler.CallShowTradeUI(itemDetails, true);
                }
                else if (slotType != SlotType.Shop && targetSlot.slotType != SlotType.Shop && slotType != targetSlot.slotType)
                {
                    //跨背包数据交换物品
                    //InventoryManager.Instance.SwapItem(Location, slotIndex, targetSlot.Location, targetSlot.slotIndex);
                }
                //清空所有高亮显示
            }
            else    //测试扔在地上
            {
                if (itemDetails.CanDropped)
                {
                    //鼠标对应世界地图坐标
                    //var pos = UniversalTool.UIPosToWorldPos(Input.mousePosition);
                    var pos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, -Camera.main.transform.position.z));
                    GameEvent.Get<ILoginUI>().InstantiateItemInScene(itemDetails.ItemID,pos);
                }
            }
            PlayerSlotInventoryPanel.instance.SelectSlotUI(slotIndex);
        }
    }
}